package cn.edu.ncut.cs.springboot.petmanagementsystem.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * CORS 跨域配置
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // 允许所有源（开发环境）
        // 注意：使用 setAllowedOriginPatterns 可以配合 allowCredentials(true)
        // 但不能使用 setAllowedOrigins(Arrays.asList("*")) 配合 allowCredentials(true)
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        
        // 允许的请求方法（包括OPTIONS预检请求）
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"));
        
        // 允许的请求头（包括所有常用请求头）
        configuration.setAllowedHeaders(Arrays.asList(
            "*",
            "Authorization",
            "Content-Type",
            "X-Requested-With",
            "Accept",
            "Origin",
            "Access-Control-Request-Method",
            "Access-Control-Request-Headers"
        ));
        
        // 允许携带凭证（用于JWT Token等）
        // 使用 setAllowedOriginPatterns 时可以设置 allowCredentials 为 true
        configuration.setAllowCredentials(true);
        
        // 预检请求的有效期（秒）
        configuration.setMaxAge(3600L);
        
        // 暴露的响应头（前端可以访问的响应头）
        configuration.setExposedHeaders(Arrays.asList(
            "Authorization",
            "Content-Type",
            "X-Total-Count",
            "Access-Control-Allow-Origin",
            "Access-Control-Allow-Credentials"
        ));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 注册所有路径的CORS配置
        source.registerCorsConfiguration("/**", configuration);
        
        return source;
    }
}
